package com.cnvp.paladin.controller;

import java.io.File;
import java.net.URL;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;

import com.cnvp.paladin.core.BaseController;
import com.cnvp.paladin.model.Equipment;
import com.cnvp.paladin.model.Netcontroller;
import com.cnvp.paladin.model.Phymapping;
import com.cnvp.paladin.model.Scene;
import com.cnvp.paladin.model.Sceneconfig;
import com.cnvp.paladin.model.SysUser;
import com.cnvp.paladin.model.SysUserRole;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

public class SceneController extends BaseController {
    boolean flag = false;
    /**
     * if the user is superadmin
     * 
     * @return return the userID
     */
    public int issuperadmin() {
        SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        int userID = currentUser.get("id");
        List<SysUserRole> sur = currentUser.getRoles();
        for (SysUserRole sr : sur) {
            if (sr.getInt("role_id") == 4)
                flag = true;
        }
        return userID;
    }
    public String sql() {
        String findSql = "(1=1) and ";
        Scene sc = getModel(Scene.class, "scene");
        String[] attrs = sc.getAttrNames();
        Object[] values = sc.getAttrValues();
        for (int i = 0; i < attrs.length; i++) {
            System.out.println(attrs[i] + values[i]);
            Object a = null;
            if (null != values[i]) {
                a = values[i].getClass();
                findSql += (attrs[i] + "=" + values[i] + " and ");
            }
        }
        return findSql;
    }
//    public void index() {
//        setAttr("page", Scene.dao.paginate(getParaToInt(0, 1), 10));
//    }
    public void index() {
        setAttr("page", Scene.dao.paginate(getParaToInt(0, 1), 10));
        int userID = issuperadmin();
        if (flag == true) {
            setAttr("page", Scene.dao.paginate(getParaToInt(0, 1), 10));
        } else {
            String sql = "where user_id =" + userID;
            setAttr("page", Scene.dao.paginate(getParaToInt(0, 1), 10, sql));
        }
    }

    public void find() {
        Map<String, Object> json = new HashMap<String, Object>();
        if (isPost()) {
            int id = getParaToInt("scene.id") == null ? -1 : getParaToInt("scene.id");
            String name = getPara("scene.name");
            String image_id = getPara("scene.image_id");
            String findSql = "(1=1) and ";
            int userID = issuperadmin();
            if (flag == true) {
                if (id != -1)
                    findSql += "id=" + id + " and ";
                if (name != null && !name.isEmpty())
                    findSql += "name like '%" + name + "%'" + " and ";
                if (image_id != null && !image_id.isEmpty())
                    findSql += "image_id like '%" + image_id + "%'" + " and ";
            } else {
                findSql += "user_id=" + userID + " and ";
                if (id != -1)
                    findSql += "id=" + id + " and ";
                if (name != null && !name.isEmpty())
                    findSql += "name like '%" + name + "%'" + " and ";
                if (image_id != null && !image_id.isEmpty())
                    findSql += "image_id like '%" + image_id + "%'" + " and ";
            }
            findSql += " (1=1);";
            List<Scene> data = Scene.dao.where(findSql);
            // 获取服务器的路径
            URL url = SceneController.class.getResource("/");
            String getPath = url.getPath().substring(0, url.getPath().length() - 16);
            // 设置头像的路径
            String path = getPath + "Static/images/protrait/";
            Scene scene = data.get(0);
            String image_id1 = scene.get("image_id");
            String portrait = path + image_id1;
            if (data.size() != 0) {
                json.put("code", "0");
                json.put("data", data+portrait);
                json.put("msg", "success");
            } else {
                json.put("code", "305");
                json.put("data", data);
                json.put("msg", "返回数据为空");
            }
        }
        renderJson(json);
    }

    public void getlist() {
        Map<String, Object> json = new HashMap<String, Object>();
        SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        int userID = currentUser.get("id");
        if (userID == 1) {
            List<Scene> data = Scene.dao.where("");
            json.put("code", "0");
            json.put("data", data);
            json.put("msg", "success");
        } else {
            String findSql = "(1=1) and ";
            findSql += "user_id=" + userID + " and ";
            findSql += " (1=1);";
            List<Scene> data = Scene.dao.where(findSql);
            json.put("code", "0");
            json.put("data", data);
            json.put("msg", "success");
        }
        renderJson(json);

    }

    public void create() {
        String is_app = getPara("is_app");
        SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        int userID = currentUser.get("id");
        Scene sc = getModel(Scene.class, "scene");
        sc.set("user_id", userID);
        if (isPost()) {
            if (null == sc.get("name")) {
                renderJson("{\"code\":\"301\",\"data\":\"\",\"msg\":\"缺少参数\"}");
            } else {
                sc.save();
                if ("1".equals(is_app)) {
                    renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"success\"}");
                } else {
                    redirect(getControllerKey());
                }
                return;
            }
        } else {
            Sceneconfig data = new Sceneconfig();
            setAttr("data", data);
            render("form.html");
        }
    }

    public void update() {
        String is_app = getPara("is_app");
        if (isPost()) {
            String flag = getPara("scene.id");
            int id = 0;
            if (flag == null && getParaToInt() != null) {
                id = getParaToInt();
            } else if (!flag.isEmpty()) {
                id = getParaToInt("scene.id");
            }
            // 检查ID是否存在
            Scene scn = Scene.dao.findById(id);
            if (scn == null) {
                renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
            } else {
                // 检验是否非空字段全部填写
                Scene sc = getModel(Scene.class, "scene").set("id", id);
                if (null == sc.get("name")) {
                    renderJson("{\"code\":\"301\",\"data\":\"\",\"msg\":\"缺少参数\"}");
                } else {
                    if (sc.update()) {
                        if ("1".equals(is_app)) {
                            renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"修改情景成功\"}");
                        } else {
                            redirect(getControllerKey());
                        }
                        return;
                    }
                }
            }
        } else {
            // renderJson("{\"code\":\"301\",\"data\":\"\",\"msg\":\"缺少参数\"}");
            setAttr("data", Scene.dao.findById(getParaToInt()));
            render("form.html");
        }
    }
    // if(null==sc.get("name")){
    // renderJson("{\"code\":\"301\"msg\":\"缺少参数\"}");
    // }else if(getModel(Equipment.class,"equipment").set("id", id).update())
    // if("1".equals(is_app)){
    // renderJson("{\"status\":\"success\"}");
    // }else{
    // redirect(getControllerKey());}
    // return;}

    public void delete() {
        String is_app = getPara("is_app");
        String flag = getPara("scene.id");
        int id = 0;
        boolean f = false;
        if (flag == null) {
            f = true;
        }
        if (f && getParaToInt() != null) {
            id = getParaToInt();
        } else if (getParaToInt("scene.id") != null) {
            id = getParaToInt("scene.id");
        }
        Scene sc = Scene.dao.findById(id);
        if (sc != null) {
            sc.delete();
            if ("1".equals(is_app)) {
                renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"删除场景成功\"}");
            } else {
                redirect(getControllerKey());
            }
        } else {
            renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
        }
    }

    // public void delete(){
    // String is_app=getPara("is_app");
    // if (Scene.dao.findById(getParaToInt()).delete())
    // if("1".equals(is_app)){
    // renderJson("{\"status\":\"success\"}");
    // }else{
    // redirect(getControllerKey());}
    // else if("1".equals(is_app)){
    // renderJson("{\"status\":\"failed\"}");
    // }else{
    // renderText("删除失败");}
    // }
    public void deleteAll() {
        String is_app = getPara("is_app");
        Integer[] ids = null;
        if (!getPara("scene.id").isEmpty()) {
            ids = getParaValuesToInt("scene.id");
        } else {
            renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
            return;
        }
        boolean flag = true;
        for (Integer id : ids) {
            Scene sc = Scene.dao.findById(id);
            if (sc != null) {
                sc.delete();
            } else {
                flag = false;
            }
        }
        if ("1".equals(is_app) && flag == true) {
            renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"批量删除场景成功\"}");
        } else if ("1".equals(is_app) && flag == false) {
            renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
        } else {
            redirect(getControllerKey());
        }
    }
/*
 * 修改每个scene的图片
 */
    public void portrait() {

        if ("POST".equals(getRequest().getMethod())) {
            // 获取上传的文件
            UploadFile pf1 = getFile("file");
            String filename2 = pf1.getFileName();
            // 获取当前时间
            Format format = new SimpleDateFormat("yyyyMMddhhmmssSSS");
            String filenamebe = format.format(new Date());
            // 取文件后缀名
            String[] token = filename2.split("\\.");
            if (token.length > 1) {
                String file_exit = token[1];
                String filename = filenamebe + "." + file_exit;
                // 获取服务器的路径
                URL url = SceneController.class.getResource("/");
                String getPath = url.getPath().substring(0, url.getPath().length() - 16);
                // 设置头像的路径
                String path = getPath + "Static/images/protrait/";
                String portrait = path + filename;
                File file = pf1.getFile();
                file.renameTo(new File(portrait));
                this.setAttr("fileName", portrait);
                // 更新数据库用户信息
                String scene_name = getPara("scene.name");
                String findSceneId = "name =" + "\"" + scene_name + "\";";
                List<Scene> sceneData = Scene.dao.where(findSceneId);
                Scene scene = sceneData.get(0);
                File deleteFile = new File(path + scene.get("image_id"));
//                scene.get("url")
//                SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
//                currentUser = SysUser.dao.findById(currentUser.get("id"));
//                File deleteFile = new File(path + currentUser.get("url"));
                if (deleteFile.exists())
                    deleteFile.delete();
                System.out.println("================fileName:" + filename);
                // 以json格式进行渲染
                Record record = new Record().set("id", scene.get("id")).set("image_id", filename);
                Db.update("cnvp_scene", record);
                String is_app = getPara("is_app");
                if ("1".equals(is_app)) {
                    renderJson("{\"code\":\"0\",\"msg\":\"success\"}");
                } else {
                    alertAndGoback("修改头像成功！");
                }
            } else {
                renderJson("{\"code\":\"301\",\"msg\":\"缺少参数\"}");
            }
        }
        Equipment data = new Equipment();
        setAttr("data", data);
        render("portrait.html");

    }

}
